// 252
package org.hwadee.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.hwadee.dto.JsonResult;
import org.hwadee.entity.Post;
import org.hwadee.entity.Result;
import org.hwadee.entity.User;
import org.hwadee.service.UserService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录页面显示
     *
     * @return 登录页面
     */
    @RequestMapping("/loginView")
    public String loginPage() {
        return "Admin/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberme = request.getParameter("rememberme");
        User user = userService.getUserByUsername(username);
        if (user == null) {
            map.put("code", 0);
            map.put("msg", "用户名无效！");
        } else if (!user.getPassword().equals(password)) {
            map.put("code", 0);
            map.put("msg", "密码错误！");
        } else if (user.getUserStatus() == 0) {
            map.put("code", 0);
            map.put("msg", "账号已禁用！");
        } else {
            // 登录成功
            map.put("code", 1);
            map.put("msg", "");
            //添加session
            request.getSession().setAttribute("user", user);
            // 添加cookie
            if (rememberme != null) {
                // 创建两个Cookie对象
                Cookie nameCookie = new Cookie("username", username);
                // 设置Cookie的有效期为3天
                nameCookie.setMaxAge(60 * 60 * 24 * 3);
                Cookie pwdCookie = new Cookie("password", password);
                pwdCookie.setMaxAge(60 * 60 * 24 * 3);
                response.addCookie(nameCookie);
                response.addCookie(pwdCookie);
            }
        }
        return new JSONObject(map).toString();
    }

    /**
     * 注册页面显示
     *
     * @return 登录页面
     */
    @RequestMapping("/registerView")
    public String registerPage() {
        return "Admin/register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult registerSubmit(HttpServletRequest request) {
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        String sexStr = request.getParameter("sex");
        String password = request.getParameter("password");
        User checkUserName = userService.getUserByUsername(username);
        if (checkUserName != null) {
            return new JsonResult<String>().fail("用户名已存在");
        }
        Integer sex;
        if (sexStr.equals("man")) {
            sex = 0;
        } else {
            sex = 1;
        }
        // 添加用户
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setSex(sex);
        user.setUserStatus(1);
        try {
            userService.register(user);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult<String>().fail("系统异常");
        }
        return new JsonResult<String>().ok("注册成功");
    }

    @RequestMapping(value = "/userList")
    public ModelAndView userList() {
        ModelAndView modelandview = new ModelAndView();
        List<User> userList = userService.getAllUsers();
        modelandview.addObject("userList", userList);
        modelandview.setViewName("Admin/User/index");
        return modelandview;
    }

    @RequestMapping(value = "search")
    public ModelAndView searchUserList(@Param("search") String search, @Param("searchType") String searchType) {
        ModelAndView modelandview = new ModelAndView();

        List<User> userList = new ArrayList<>();
        if (searchType.equals("userId")) {
            boolean result = search.matches("[0-9]+");
            if (result == true) {
                Integer userId = Integer.parseInt(search);
                User user = userService.getUserById(userId);
                if (user != null) {
                    userList.add(user);
                }
            }
        } else if (searchType.equals("username")) {
            User user = userService.getUserByUsername(search);
            if (user != null) {
                userList.add(user);
            }
        } else {
            userList = userService.getUsersByNickname(search);
        }
        modelandview.addObject("userList", userList);

        modelandview.setViewName("Admin/User/index");
        return modelandview;
    }

    /**
     * 基本信息页面显示
     *
     * @param session session
     * @return 基本信息页面
     */
    @RequestMapping(value = "/profile")
    public ModelAndView userProfileView(HttpSession session) {

        ModelAndView modelAndView = new ModelAndView();
        User sessionUser = (User) session.getAttribute("user");
        User user = userService.getUserById(sessionUser.getUserId());
        modelAndView.addObject("user", user);
        modelAndView.setViewName("Admin/User/profile");
        return modelAndView;
    }

    /**
     * 编辑个人信息页面显示
     *
     * @param session session
     * @return 编辑个人信息页面
     */
    @RequestMapping(value = "/editProfile")
    public ModelAndView editProfile(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView();
        User loginUser = (User) session.getAttribute("user");
        User user = userService.getUserById(loginUser.getUserId());
        modelAndView.addObject("user", user);

        modelAndView.setViewName("Admin/User/editProfile");
        return modelAndView;
    }

    /**
     * 编辑用户提交
     *
     * @param user    用户
     * @param session session
     * @return 用户信息
     */
    @RequestMapping(value = "/saveProfile", method = RequestMethod.POST)
    public String saveProfile(User user, HttpSession session) {
        User dbUser = (User) session.getAttribute("user");
        user.setUserId(dbUser.getUserId());
        userService.updateUser(user);
        session.setAttribute("user", user);
        return "redirect:/user/profile";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/user/loginView";
    }

    /**
     * 检查用户名是否存在
     *
     * @param request request
     * @return 检查结果
     */
    @RequestMapping(value = "/checkUserName", method = RequestMethod.POST, produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String checkUserName(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String username = request.getParameter("username");
        User user = userService.getUserByUsername(username);
        int id = Integer.parseInt(request.getParameter("id"));
        //用户名已存在,但不是当前用户(编辑用户的时候，不提示)
        if (user != null) {
            if (user.getUserId() != id) {
                map.put("code", 1);
                map.put("msg", "用户名已存在！");
            }
        } else {
            map.put("code", 0);
            map.put("msg", "");
        }
        return new JSONObject(map).toString();
    }

    /**
     * 删除用户
     *
     * @param id 用户id
     * @return 用户页面
     */
    @RequestMapping(value = "/delete/{id}")
    public String deleteUser(@PathVariable("id") Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user.getUserId() != id) {
            userService.deleteUserById(id);
            return "redirect:/user/userList";
        }
        return "redirect:/user/userList";
    }

    /**
     * 恢复用户
     *
     * @param id 用户id
     * @return 用户页面
     */
    @RequestMapping(value = "/recovery/{id}")
    public String recoveryUser(@PathVariable("id") Integer id) {
        userService.recoveryUserById(id);
        return "redirect:/user/userList";
    }

}
